package com.siwei.infoextract.wrapper.featureextract;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.siwei.infoextract.wrapper.parser.Constraints;
import com.siwei.infoextract.wrapper.parser.DomNode;
import com.siwei.infoextract.wrapper.parser.IgnoreTags;

public class DomTreeNormalizer {
	private DomNode domNode;

	public DomTreeNormalizer(DomNode domNode) {
		this.domNode = domNode;
	}

	public void normalize() {
		internalNormalize(this.domNode);
	}

	private void internalNormalize(DomNode root) {
		InnerTextFeatureExtractor innerTextExtractor = new InnerTextFeatureExtractor();
		String innerText = (String) innerTextExtractor.extract(root);

		int childCount = root.getChildrenCount();
		DomNode parent = root.getParent();

		
		
		if (parent == null ||
				root.getName().equals(Constraints.TEXT_TAG_NAME) ||
				(innerText != null && !innerText.trim().equals("") && !innerText.trim().equals("" + (char)160))) {
			if (!IgnoreTags.contains(root.getName())) {
				List<DomNode> childNodes = new ArrayList<DomNode>();
				childNodes.addAll(root.getNodes());

				for (Iterator<DomNode> iter = childNodes.iterator(); iter.hasNext();) {
					internalNormalize(iter.next());
				}
				return;
			}
		}

		DomNode nextSibling = root.getNextSibling();
		parent.removeChild(root);

		List<DomNode> childNodes = root.getNodes();

		for (Iterator<DomNode> iter = childNodes.iterator(); iter.hasNext();) {
			parent.addChild(nextSibling, iter.next());
		}

		for (Iterator<DomNode> iter = childNodes.iterator(); iter.hasNext();) {
			internalNormalize(iter.next());
		}
	}
}
